package com.sky.aspect;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.util.EntityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * 输出对应的请求，并打印出对应的参数
 */
@Aspect
@Component
@Slf4j
public class ControllerLogInfoAspect {
    //这里只打印带有
    @Pointcut("execution(* com.sky.controller..*(..)) && @annotation(io.swagger.annotations.ApiOperation)")
    public void pt(){}

    @Before("pt()")
    public void logBeforeControllerMethods(JoinPoint joinPoint){
        //获取方法签名
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();

        //获取方法上的注解：
        String input="";
        ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
        if(apiOperation != null){
            input=apiOperation.value()+":";
        }
        //获取方法上的参数
        Object[] args=joinPoint.getArgs();
        //过滤掉一些不能打印的参数
        Object[] filteredArgs = Arrays.stream(args)
                .filter(arg -> !(arg instanceof HttpServletResponse))
                .toArray();
        log.info(input+ JSONObject.toJSONString(filteredArgs));

    }
}
